//
//  TDRegistViewController.m
//  TFB
//
//  Created by Nothing on 15/3/16.
//  Copyright (c) 2015年 TD. All rights reserved.
//

#import "TDRegistViewController.h"
#import "TDHttpEngine.h"
#import "MKNetworkKit.h"

@interface TDRegistViewController ()
{
    MKNetworkEngine *_mkNetworkEngine;
    
    NSTimer *_timer2222;
    
//    BOOL isAgree;
    //
    dispatch_queue_t queue ;
    dispatch_source_t _timer;
}
@end

@implementation TDRegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] init];
    backBtn.title = @"返回";
    [backBtn setTintColor:[UIColor whiteColor]];
    self.navigationItem.backBarButtonItem = backBtn;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(getVerLabelClickWithLabel:)];
    self.getVerLabel.userInteractionEnabled = YES;
    [self.getVerLabel addGestureRecognizer:tap];
    
    _mkNetworkEngine = [[MKNetworkEngine alloc] init];
    
    
    //[self yanzhengmaYanzhengTest];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//获取验证码
- (void)getVerLabelClickWithLabel:(id)sender
{
    [self timerFireMethod];
    //[self onTimerWithButton:sender];
    
    [TDHttpEngine requestForGetMsgCodeWithCustMobile:@"" codeType:@"" complete:^(BOOL succeed, NSString *msg, NSString *cod) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (succeed) {
            NSLog(@"%@", msg);
            
            
        }
        else{
            
        }
        [self.view makeToast:msg duration:2.0f position:@"center"];
    }];
}

- (IBAction)getVerifyNumBtnClick:(id)sender {
    //[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
//    [dic setValue:@"13273901442" forKey:@"custMobile"];
//    [dic setValue:@"01" forKey:@"codeType"];
//    
//    NSDictionary *diction = [self jsonWithDic:dic];
//    MKNetworkOperation *operation = [_mkNetworkEngine operationWithURLString:@"http://192.168.0.59:8080/mpcctp/SY0001.json" params:diction httpMethod:@"POST"];
//    __weak MKNetworkOperation *weakOperation = operation;
//    [weakOperation addCompletionHandler:^(MKNetworkOperation *completedOperation) {
//        NSLog(@"%@", weakOperation.responseString);
//    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
//        NSLog(@"error---> %@\r errmasage--->%@", error, [error localizedDescription]);
//    }];
//    [_mkNetworkEngine enqueueOperation:operation];
    
//    [TDHttpEngine requestForGetMsgCodeWithCustMobile:@"13273901442" codeType:@"01" complete:^(BOOL succeed) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        if (succeed) {
//            NSLog(@"已发送");
//        }
//    }];
    
    
    [self timerFireMethod];
    
//    [TDHttpEngine requestForGetMsgCodeWithCustMobile:@"13273901442" codeType:@"01" complete:^(BOOL succeed, NSString *msg) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        if (succeed) {
//            NSLog(@"%@", msg);
//            
//            
//        }
//        else{
//            
//        }
//        [self.view makeToast:msg duration:2.0f position:@"center"];
//    }];
}

- (void)onTimerWithButton:(id)sender
{
    _timer2222 = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeBtnTitle) userInfo:nil repeats:YES];
}

- (void)changeBtnTitle
{
    static int title = 60;
    title --;
    self.getVerLabel.text = [NSString stringWithFormat:@"%d s", title];
    if (title == 0) {
        [_timer2222 invalidate];
        self.getVerLabel.text = @"重新获取";
        title = 60;
    }
}

- (NSDictionary *)jsonWithDic:(id)sender
{
    NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *smallDic = [NSMutableDictionary dictionaryWithObject:sender forKey:@"REQ_BODY"];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:smallDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    [jsonDic setObject:jsonStr forKey:@"REQ_MESSAGE"];
    return jsonDic;
}

//- (IBAction)checkBtnClick:(id)sender {
//    if (!isAgree) {
//        [self.checkBtn setBackgroundImage:[UIImage imageNamed:@"checkbox_select"] forState:UIControlStateNormal];
//        isAgree = YES;
//        return;
//    }
//    if (isAgree)
//    {
//        [self.checkBtn setBackgroundImage:[UIImage imageNamed:@"checkbox_normal"] forState:UIControlStateNormal];
//        isAgree = NO;
//        return;
//    }
//}
//
//- (IBAction)agreementBtnClick:(id)sender {
//
//}

- (IBAction)commitBtnClick:(id)sender {
    
    NSString *loginPwd = [self.loginPwdTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *againLoginPwd = [self.againLonginPwdTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (loginPwd.length < 6) {
        [self.view makeToast:@"密码不能小于6位" duration:2.0f position:@"center"];
        return;
    }
    if (![loginPwd isEqualToString:againLoginPwd]) {
        [self.view makeToast:@"两次输入密码不一致" duration:2.0f position:@"center"];
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [TDHttpEngine requestForRegistWithCustMobile:self.mobileNum custPwd:[_loginPwdTF.text md5] complete:^(BOOL succeed, NSString *msg, NSString *cod) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.view makeToast:msg duration:2.0f position:@"center"];
        if (succeed) {
            [self performSelector:@selector(popToLogin) withObject:self afterDelay:2.0f];
        }
        else{
            
        }
    }];
    
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
//    [dic setValue:@"13273901442" forKey:@"custMobile"];
//    [dic setValue:@"111111" forKey:@"custPwd"];
//    [dic setObject:@"鲁" forKey:@"custName"];
//    [dic setObject:@"431381198109106573" forKey:@"certificateNo"];
//    
//    NSDictionary *diction = [self jsonWithDic:dic];
//    MKNetworkOperation *operation = [_mkNetworkEngine operationWithURLString:@"http://192.168.0.59:8080/mpcctp/SY0002.json" params:diction httpMethod:@"POST"];
//    __weak MKNetworkOperation *weakOperation = operation;
//    [weakOperation addCompletionHandler:^(MKNetworkOperation *completedOperation) {
//        NSLog(@"%@", weakOperation.responseString);
//    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
//        NSLog(@"error---> %@\r errmasage--->%@", error, [error localizedDescription]);
//    }];
//    [_mkNetworkEngine enqueueOperation:operation];
    
    
}



//验证码跳秒方法
- (void)timerFireMethod
{
    _getVerLabel.userInteractionEnabled = NO;
    __block int timeout = 59; //倒计时时间
    queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                _getVerLabel.userInteractionEnabled = YES;
                _getVerLabel.text = @"重新获取验证码";
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d秒", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                _getVerLabel.text = [NSString stringWithFormat:@"%@",strTime];
                _getVerLabel.textColor = [UIColor blackColor];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)popToLogin
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
